// alliance//receiveAllianceCoupon/index.js
const utils = require('../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addedMerlist: [],
    allianceid: 0,
    allianceName: '',
    staffid: 0,
    windowHeight: 500,
    classList: [],
    storeiid: 0,
    aggre: 1,
    CurrentPage: 1,
    loadingMoreHidden: 1,
    isAccredit: false,
    costMoney: 0,
    couponMoney: 0,
    merchants: 0,
    showDialog: false,
    isAuth: 0,
    code: '',
    mobile: ''
  },
  tapClassSelect: function (e) {
    let cid = e.currentTarget.dataset.cid;
    this.setData({
      storeiid: cid
    })
    this.getAllianceStaffList(this.data.allianceid);
  },
  //获取手机号
  getPhoneNumber: function (e) {
    let that = this;
    utils.getMobile(e, function (callback) {
      that.setData({
        mobile: callback
      })
    });
  },
  // 获取联盟信息
  getAllianceInfo: function (allianceid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Alliance/GetAlliance?allianceId=' + allianceid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            allianceName: res.data.Data.Name,
            isAuth: res.data.Data.IsAuth
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 获取店铺行业
  getIndustryList: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetIndustryList?storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            classList: res.data.Data
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  getSaleInfo: function (allianceId) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/alliance/GetSaleInfo?allianceId=' + allianceId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            costMoney: res.data.Data.CardMoney,
            couponMoney: res.data.Data.CouponMoney,
            merchants: res.data.Data.StaffCount
          })
        }
      }
    })
  },

  // 获取联盟商家及礼包
  getAllianceStaffList: function (allianceId) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Alliance/GetAllianceStaffList?allianceId=' + allianceId + '&industryId=' + that.data.storeiid + '&page=' + that.data.CurrentPage,
      success: function (res) {
        if (res.data.Code == 0) {
          let addedMerlist = res.data.Data.Items;
          if (that.data.CurrentPage != 1) {
            var preGoods = that.data.addedMerlist
            addedMerlist = preGoods.concat(addedMerlist);
          }
          for (let i = 0; i < addedMerlist.length; i++) {
            if (addedMerlist[i].Avater) {
              addedMerlist[i].Avater = utils.formatAvater(addedMerlist[i].Avater, 'https://static.711688.net.cn/upload/card/source/');
            }
            let carditems = addedMerlist[i].CardItemList;
            if (carditems.length > 0) {
              for (let j = 0; j < carditems.length; j++) {
                var detailpics = carditems[j].DetailPics;
                carditems[j].showDetailPics = '';
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  carditems[j].showDetailPics = list[0];
                }
              }
            }
            let coupons = addedMerlist[i].CouponTypeList;
            if (coupons.length > 0) {
              for (let j = 0; j < coupons.length; j++) {
                var detailpics = coupons[j].DetailPics;
                coupons[j].showDetailPics = '';
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  coupons[j].showDetailPics = list[0];
                }
              }
            }
            let card = addedMerlist[i].Card;
            if (card) {
              card.Discount = card.Discount * 0.1;
              card.Discount = card.Discount.toFixed(1);
              var detailpics = card.DetailPics;
              if (detailpics) {
                card.showDetailPics = '';
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  card.showDetailPics = list[0];
                }
              }

            }
          }
          that.setData({
            addedMerlist: addedMerlist,
            loadingMoreHidden: res.data.Data.TotalPages
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 优惠券详情
  toCouponDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&coupontypeid=' + coupontypeid,
    })
  },
  // 消费卡详情
  toCardItemDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&ids=' + id,
    })
  },

  // 一键领取
  receivePackage22: function () {
    let that = this;
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      let back = '/merchant/alliance/receiveAllianceCoupon/index';
      wx.navigateTo({
        url: '/pages/accredit/index?back=' + back + '&staffid=' + that.data.staffid + '&allianceId=' + that.data.allianceid
      })
    } else {
      that.setData({
        showDialog: !that.data.showDialog
      })
    }
  },
  // 一键领取授权手机号领取礼包后再授权头像昵称
  receivePackage: function () {
    let that = this;
    if (that.data.mobile) {
      if (that.data.isAuth) {
        that.setData({
          showDialog: !that.data.showDialog
        })
      } else {
        that.receivePackageConfirm();
      }
    }
  },

  // 确认领取
  receivePackageConfirm: function () {
    let that = this;
    let code = that.data.code;
    let mobile = that.data.mobile;
    let isAuth = that.data.isAuth;
    if (isAuth) {//需要授权码
      if (!code) {
        that.checkWrite('请输入授权码');
        return;
      } else {
        code = parseInt(code);
      }
    } else {
      code = 0;
    }
    if (!mobile) {
      that.checkWrite('请授权手机号');
      return;
    }
    wx.showLoading({
      title: '正在领取',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Alliance/ReceivePackage',
      data: {
        staffId: that.data.staffid,
        allianceId: that.data.allianceid,
        uid: app.globalData.userInfo.Uid,
        isAuto: that.data.aggre,
        code: code,
        mobile: mobile
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.showToast({
            title: '领取成功',
            duration: 2000
          })
          setTimeout(function () {
            let isAccredit = that.data.isAccredit;
            if (!isAccredit) {
              let back = '/pages/weijieke/cardList/index';
              wx.navigateTo({
                url: '/pages/accredit/index?back=' + back + '&staffid=' + that.data.staffid + '&allianceId=' + that.data.allianceid
              })
            }
          }, 2000);
        } else if (res.data.Code == 302) {//已经是联盟会员
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                that.receiveAllianceCouponRefresh(that.data.allianceid);
                wx.redirectTo({
                  url: '/pages/weijieke/cardList/index',
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
            confirmText: '点击查看'
          })
        }
      }
    })
  },
  // 领取联盟内更新的优惠券
  receiveAllianceCouponRefresh: function (allianceId) {
    let cardId = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + "/api/alliance/ReceivePackage?isRefresh=1&staffId=" + cardId + '&uid=' + app.globalData.userInfo.Uid + '&allianceId=' + allianceId,
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showToast({
            title: '领取成功',
            mask: true
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false,
          })
        }
      },
    })
  },

  closedialog: function () {
    this.setData({
      showDialog: !this.data.showDialog
    })
  },

  bindCode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let params = decodeURIComponent(options.scene);
    var windowHeight = wx.getSystemInfoSync().windowHeight;
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let plist = '';
      if (params.indexOf('p-') != -1) {
        let param = params.match(/p-(\S*)/)[1];//参数
        plist = param.split('_');
      }else{
        let param = params.match(/p=(\S*)/)[1];//参数
        plist = param.split('#');
      }
      that.getAllianceInfo(plist[1]);
      that.getAllianceStaffList(plist[1]);
      that.getSaleInfo(plist[1]);
      that.setData({
        allianceid: plist[1],
        staffid: plist[0],
        windowHeight: windowHeight
      })
    } else {
      that.getAllianceInfo(options.allianceid);
      that.getAllianceStaffList(options.allianceid);
      that.getSaleInfo(options.allianceid);
      that.setData({
        allianceid: options.allianceid,
        staffid: options.id,
        windowHeight: windowHeight
      })
    }

    that.getIndustryList();
    utils.isAccredit(function (isAccredit) {
      that.setData({
        isAccredit: isAccredit
      })
    });
    if (options.showDialog) {
      that.setData({
        showDialog: options.showDialog
      })
    }
  },
  aggre: function () {
    let aggre = this.data.aggre;
    if (aggre == 1) {
      aggre = 0;
    } else {
      aggre = 1;
    }
    this.setData({
      aggre: aggre
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.Mobile) {
      this.setData({
        mobile: app.globalData.userInfo.Mobile
      })
    }
  },

  loadMore: function () {
    var that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.CurrentPage < that.data.loadingMoreHidden) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      that.getAllianceStaffList(that.data.allianceid);
    } else {
      return
    }
  },
  //填写判断
  checkWrite: function (str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  }
})